
###Clear R--------------------
rm(list=ls())

###Function to recode variables to range from lowest (0) to highest (1) observation---------------------
zero1 <- function(x, minx=NA, maxx=NA){
  res <- NA
  if(is.na(minx)) res <- (x - min(x,na.rm=T))/(max(x,na.rm=T) -min(x,na.rm=T))
  if(!is.na(minx)) res <- (x - minx)/(maxx -minx)
  res
}

####function to install packages if they don't exist----------------
ipak <- function(pkg){
  new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
  if (length(new.pkg)) 
    install.packages(new.pkg, dependencies = TRUE)
  sapply(pkg, require, character.only = TRUE)
}

# usage
packages <- c("psych", "ggplot2", "interplot", "MASS", "foreign",  "car", "stringr", "stargazer", "xtable", "moments", "dplyr")
ipak(packages)

#load data
load("Study6_DK_Replication.RData")

### Treatment variables----------------
data$leftrightcondition <- NA
data$leftrightcondition[is.na(data$q15a)==F] = 'Left Supports'
data$leftrightcondition[is.na(data$q15b)==F] = 'Right Supports'
data$leftrightcondition[is.na(data$q15c)==F] = 'Left Supports'
data$leftrightcondition[is.na(data$q15d)==F] = 'Right Supports'

data$complex <- NA
data$complex[is.na(data$q15a)==F] = 'TIPI'
data$complex[is.na(data$q15b)==F] = 'TIPI'
data$complex[is.na(data$q15c)==F] = 'Pill'
data$complex[is.na(data$q15d)==F] = 'Pill'

### Partisan Social Identity Strength=====================
data$identity1 <- rowMeans(data.frame(5-as.numeric(data$q5),5-as.numeric(data$q7)),na.rm=T)
data$identity2<- rowMeans(data.frame(5-as.numeric(data$q6),5-as.numeric(data$q8)),na.rm=T)
data$identitystrength <-zero1(rowMeans(with(data,data.frame(identity1,identity2)),na.rm=T))

### Dependent variable -------------
data$ownside <- (data$leftright=='Left' &  data$leftrightcondition=='Left Supports')|(data$leftright=='Right' &  data$leftrightcondition=='Right Supports')
data$supportttip <- zero1(6-rowMeans(mapply(as.numeric,data.frame(data$q15a,data$q15b,data$q15c,data$q15d)),na.rm=T))

### Cognitive Reflection Test----------------
data$cr1 <- ifelse(data$q29==5,1,0)
data$cr2 <- ifelse(data$q30==5,1,0)
data$cr3 <- ifelse(data$q31==47,1,0)
data$CRTall <- rowSums(with(data,data.frame(cr1,cr2,cr3)))
data$CRTall <- zero1(data$CRTall)

#make numerical variables---------
data$ownside<-as.numeric(data$ownside)
data$inparty<-as.numeric(data$ownside)


save(data,file="Study6_data.RData")
